/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.UserBean;
import ejb.UserBeanLocal;
import entities.User;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import utils.UtilsBean;

/**
 *
 * @author Alejandro
 */
@ManagedBean
@RequestScoped
public class LoginManagedBean {

    private FacesContext context;
    @EJB
    private UserBeanLocal userBean;
    private User user;
    private Boolean logged;

    public LoginManagedBean() {

        context = FacesContext.getCurrentInstance();
        userBean = new UserBean();
        user = new User();
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String notRegistred() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "OK";
    }

    public String registred() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
//        return "OK";
        String navigation = "LOGIN_ERROR";
        //Segunda validacion en servidor
        if (user.getEmail() == null || user.getEmail().isEmpty() || user.getPass() == null || user.getPass().isEmpty() || (user.getEmail().length()) > 255 || (user.getPass().length()) > 15) {
            FacesContext.getCurrentInstance().addMessage("msgLogin", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Contacte con el administrador"));
            return navigation;
        }
        User aux = userBean.findByEmail(user);

        if (aux == null) {//Usuario no existe
            FacesContext.getCurrentInstance().addMessage("msgLogin", new FacesMessage(FacesMessage.SEVERITY_INFO, "El email no existe", "Porfavor registrese"));
        } else if (aux.getStatus().equals(0)) {
            FacesContext.getCurrentInstance().addMessage("msgLogin", new FacesMessage(FacesMessage.SEVERITY_INFO, "El usuario esta dado de baja. Contacte con el administrador", ""));
            return navigation;
        } else if (aux.getPass().equals(UtilsBean.sha512(user.getPass()))) {//Todo OK
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(Constants.ACTUAL_USER, aux);
            navigation = "OK";
        } else {//Contraseña incorrecta o cualquier otro caso
            FacesContext.getCurrentInstance().addMessage("msgLogin", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Clave incorrecta", "Revise el bloqueo de mayuscula"));
        }
        return navigation;
    }

    public String guest() {
        return "OK";
    }

    public String goToLogin() {
        return "LOGIN";
    }
}
